package thread.lock;



import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {
    public static void main(String[] args) {
        //传入true ，此时就是一个公平锁
        ReentrantLock lock = new ReentrantLock(true);
        Thread t1 = new Thread(()  -> {
            lock.lock();//代码从这里开始枷锁，直接碰到unlock释放锁
            //互斥代码块
            try {
                System.out.println(Thread.currentThread().getName() + "获取到锁，其他线程等待");
                Thread.sleep(8000);
            }catch (InterruptedException e){
                throw  new RuntimeException(e);
            }finally {
                lock.unlock();
            }
            System.out.println(Thread.currentThread().getName()+ "释放锁");
        },"丰岩");
        t1.start();
        Thread t2 = new Thread(() ->{
            boolean isLocked = false;
            try {
                isLocked = lock.tryLock(3000, TimeUnit.MICROSECONDS);
            }catch (InterruptedException e){
                e.printStackTrace();
            }finally {
                if (isLocked){
                    //只有获取锁成功的线程才需要执行unLock方法
                    lock.unlock();
                }
            }
            System.out.println("不爱我是吧");
        },"阿龙" );
        t2.start();
    }
}
